import 'package:audioplayers/audioplayers.dart';
typedef MSCallBack = void Function(PlayerState state);
class MSAudioPlayerUtil{
  static final MSAudioPlayerUtil _instance =MSAudioPlayerUtil._();
  final player = AudioPlayer();
   MSCallBack? c = null;
  final Map<String,List<MSCallBack>> _listeners = {};
  MSAudioPlayerUtil._(){
    player.onPlayerComplete.listen((event) {
      if(_listeners[current] != null) {
        for (var callback in _listeners[current]!) {
          callback(PlayerState.stopped);
        }
      }
    });
  }
  String? current;
  factory MSAudioPlayerUtil(){
    return _instance;
  }

  play(String path) async{
    if(player.state ==PlayerState.playing){
      await player.stop();
      if(_listeners[current]!= null){
        for (var callback in _listeners[current]!) {
          callback(PlayerState.stopped);
        }
      }
      if(path != current){
        await player.play(DeviceFileSource(path));
        current = path;
        if(_listeners[current] != null){
          for (var callback in _listeners[current]!) {
            callback(PlayerState.playing);
          }
        }
      }
    }else {
      await player.play(DeviceFileSource(path));
      current = path;
      if(_listeners[current] != null){
        for (var callback in _listeners[current]!) {
          callback(PlayerState.playing);
        }
      }

    }
  }

  stop() async{
        await player.stop();
        for (var callback in _listeners[current]!) {
          callback(PlayerState.stopped);
        }
  }

  addListener({required String key,required MSCallBack callBack}){
    c = callBack;
    if(_listeners.containsKey(key)){
      _listeners[key]!.add(callBack);
    }else{
      _listeners.addEntries([MapEntry(key, [callBack])]);
    }

  }

  removeListener(String key,MSCallBack callback){
    if(_listeners.containsKey(key)){
      _listeners[key]!.remove(callback);
    }
  }
}